package dai.samples.rabbit.retry.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 模拟重试
 * @author daify
 * @date 2019-07-24 16:50
 **/
@Configuration
public class RetryConfig {


    /**
     * 重试的队列
     */
    public final static String RETRY_QUEUE = "retry.queue";

    /**
     * 重试的交换器
     */
    public final static String RETRY_EXCHANGE = "retry.exchange";

    /**
     * 处理业务的路由key
     */
    public final static String RETRY_KEY = "retry.key";

    /**
     * 超时时间
     */
    private static final Long QUEUE_EXPIRATION = 4000L;


   
    /**
     * 重试的交换器
     * @return
     */
    @Bean
    DirectExchange retryExchange() {
        return new DirectExchange(RETRY_EXCHANGE);
    }


    /**
     * 重试的队列
     * @return
     */
    @Bean
    public Queue retryQueue() {
        // 设置超时队列
        return QueueBuilder.durable(RETRY_QUEUE)
                // DLX，dead letter发送到的exchange ,设置死信队列交换器到处理交换器
                .withArgument("x-dead-letter-exchange", WorkConfig.WORK_EXCHANGE)
                // dead letter携带的routing key，配置处理队列的路由key
                .withArgument("x-dead-letter-routing-key", WorkConfig.WORK_KEY)
                // 设置过期时间
                .withArgument("x-message-ttl", QUEUE_EXPIRATION)
                .build();
    }


    /**
     * 绑定处理队列的数据监听工作
     * @return
     */
    @Bean
    public Binding retryBinding() {
        return BindingBuilder
                .bind(retryQueue())
                .to(retryExchange())
                .with(RETRY_KEY);
    }

}
